package com.pdd.autoconf.config;

import com.pdd.autoconf.scope.PddScope;
import com.pdd.autoconf.watchers.PddZkNodeWatcher;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author:liyangpeng
 * @date:2020/9/1 11:26
 */
@Configuration
@ConditionalOnProperty(prefix="pdd.config",value="enable",havingValue = "true")
@ConditionalOnBean(PddZkAutoProperties.class)
public class PddZkAutoConfig {

    @Bean
    public PddScope pddScope(){
        return new PddScope();
    }

    @Bean
    public CuratorFramework getZkClient(PddZkAutoProperties pddZkAutoProperties,PddScope pddScope) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(pddZkAutoProperties.getBaseSleepTimeMs(), pddZkAutoProperties.getMaxRetries());
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(pddZkAutoProperties.getNodes(), pddZkAutoProperties.getSessionTimeoutMs(), pddZkAutoProperties.getConnectionTimeoutMs(), retryPolicy);
        curatorFramework.start();
        TreeCache cache = TreeCache.newBuilder(curatorFramework, pddZkAutoProperties.getBasepath()).build();
        cache.getListenable().addListener(new PddZkNodeWatcher(pddScope));
        cache.start();
        return curatorFramework;
    }
}
